<!--
 * @Descripttion: 商品管理
 * @Author: xiao li
 * @Date: 2020-07-06 12:17:07
 * @LastEditors: xiao li
 * @LastEditTime: 2021-11-19 18:08:51
-->
<template>
  <div class="lb-goods-list">
    <top-nav />
    <div class="page-main">
      <el-row class="page-top-operate">
        <el-button
          @click="toChange(1)"
          :type="searchForm.type === 1 ? 'primary' : ''"
          plain
          size="medium"
          >出售中（{{ sale_ing }}）</el-button
        >
        <el-button
          @click="toChange(2)"
          :type="searchForm.type === 2 ? 'primary' : ''"
          plain
          size="medium"
          >已售罄（{{ sale_out }}）</el-button
        >
        <el-button
          @click="toChange(3)"
          :type="searchForm.type === 3 ? 'primary' : ''"
          plain
          size="medium"
          >仓库中（{{ sale_end }}）</el-button
        >
      </el-row>

      <el-row class="page-search-form">
        <el-form :inline="true" :model="searchForm" ref="searchForm">
          <el-form-item label="部门" prop="">
            <el-cascader
              v-model="companyArr"
              :options="companyOptions"
              :props="{ checkStrictly: true, value: 'id', label: 'name' }"
              clearable
            ></el-cascader>
          </el-form-item>
          <el-form-item label="分类" prop="">
            <el-cascader
              v-model="cateArr"
              :options="cateOptions"
              :props="{ checkStrictly: true, value: 'id', label: 'title' }"
              clearable
            ></el-cascader>
          </el-form-item>
          <el-form-item label="商品名称" prop="name">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入商品名称"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <lb-button
              size="medium"
              type="primary"
              icon="el-icon-search"
              style="margin-right: 5px"
              @click="getTableDataList(1)"
              >{{ $t('action.search') }}</lb-button
            >
            <lb-button
              size="medium"
              icon="el-icon-refresh-left"
              style="margin-right: 5px"
              @click="resetForm('searchForm')"
              >{{ $t('action.reset') }}</lb-button
            >
          </el-form-item>
        </el-form>
      </el-row>

      <el-row class="page-top-operate">
        <lb-button
          size="medium"
          type="primary"
          opType="add"
          @click="$router.push('/malls/edit')"
          >添加商品</lb-button
        >
        <!-- <lb-button size='medium' type='primary' opType='del' @click="clearQrCode">清除商品二维码</lb-button> -->
      </el-row>
      <el-table
        v-loading="loading"
        ref="multipleTable"
        :data="tableData"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="id" label="ID"> </el-table-column>
        <el-table-column
          prop="name"
          width="200"
          show-overflow-tooltip
          label="商品名"
        >
        </el-table-column>
        <el-table-column prop="name" width="100" label="封面图">
          <template slot-scope="scope">
            <lb-image :src="scope.row.cover[0]" />
          </template>
        </el-table-column>
        <el-table-column prop="cate_text" label="所属分类">
          <template slot-scope="scope">
            <span>{{ scope.row.cate_text || '暂无分类' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="price_text" label="价格"> </el-table-column>
        <el-table-column prop="all_stock" label="库存">
          <template slot-scope="scope">
            <div class="hover-class flex-column">
              <div>{{ scope.row.all_stock }}</div>
              <div
                @click="toEditSpec(scope.row.spe_info)"
                class="iconfont iconxiugai c-link f-paragraph mt-md"
              >
                修改
              </div>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column
              prop="sale_count"
              width="120"
              label="总销量">
            </el-table-column> -->
        <el-table-column prop="true_sale_count" width="120" label="实际销量">
        </el-table-column>
        <el-table-column prop="company_count_text" label="销售部门(个)">
        </el-table-column>
        <el-table-column prop="status" label="是否上架">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="upperAndDelGoods(scope.row.status, [scope.row.id])"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="index_show" label="首页推荐">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.index_show"
              :active-value="1"
              :inactive-value="0"
              @change="
                upperAndDelGoods(
                  scope.row.index_show,
                  [scope.row.id],
                  'index_show'
                )
              "
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="是否推荐">
          <template slot-scope="scope">
            <span>{{ scope.row.recommend ? '是' : '否' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="top" label="排序值"> </el-table-column>
        <el-table-column prop="create_time" width="120" label="创建时间">
          <template slot-scope="scope">
            <div>{{ scope.row.create_time | handleTime(1) }}</div>
            <div>{{ scope.row.create_time | handleTime(2) }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="address" width="180px" label="操作">
          <template slot-scope="scope">
            <div class="table-operate">
              <lb-button
                size="mini"
                plain
                type="primary"
                @click="$router.push('/malls/edit?id=' + scope.row.id)"
                >{{ $t('action.edit') }}</lb-button
              >
              <lb-button
                size="mini"
                plain
                type="danger"
                @click="confirmDelGoods([scope.row.id])"
                >{{ $t('action.delete') }}</lb-button
              >
              <lb-button
                size="mini"
                plain
                type="success"
                @click="$router.push('/malls/newAssemble?id=' + scope.row.id)"
                >拼团</lb-button
              >
              <lb-button
                size="mini"
                plain
                type="warning"
                @click="$router.push('/malls/wholesale?id=' + scope.row.id)"
                >批发价</lb-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <lb-page
        :page="searchForm.page"
        :pageSize="searchForm.limit"
        :total="total"
        :selected="multipleSelection.length"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      >
        <lb-button size="mini" type="primary" @click="batchUpperAndDel(1)"
          >批量上架</lb-button
        >
        <lb-button size="mini" type="warning" @click="batchUpperAndDel(0)"
          >批量下架</lb-button
        >
        <lb-button size="mini" type="danger" @click="batchUpperAndDel(-1)"
          >批量删除</lb-button
        >
      </lb-page>

      <el-dialog
        title="修改库存"
        :visible.sync="showSpecDialog"
        width="600px"
        center
        :before-close="beforeClose"
      >
        <div class="flex-center">
          <el-table
            :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
            tooltip-effect="dark"
            :data="specsTable"
            style="width: 100%"
          >
            <el-table-column
              prop="title"
              label="规格组合名称"
            ></el-table-column>
            <el-table-column prop="stock" label="库存" width="150">
              <template slot-scope="scope">
                <el-input-number
                  size="mini"
                  v-model="scope.row.stock"
                  :controls="false"
                  :precision="0"
                  :min="0"
                ></el-input-number>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="beforeClose">{{ $t('action.cancel') }}</el-button>
          <el-button type="primary" @click="submitFormInfo()">{{
            $t('action.comfirm')
          }}</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      loading: false,
      companyArr: [],
      cateArr: [],
      searchForm: {
        company: '',
        cate: '',
        name: '',
        page: 1,
        limit: 10,
        type: 1
      },
      companyOptions: [
        {
          id: 0,
          name: '全部'
        }
      ],
      cateOptions: [
        {
          id: 0,
          title: '全部'
        }
      ],
      tableData: [],
      total: 0,
      sale_ing: 0,
      sale_end: 0,
      sale_out: 0,
      multipleSelection: [],
      showSpecDialog: false,
      specsTable: []
    }
  },
  created () {
    this.getSelectOptions()
  },
  activated () {
    this.getTableDataList()
  },
  methods: {
    resetForm (name) {
      this.companyArr = []
      this.cateArr = []
      this.$refs[name].resetFields()
      this.getTableDataList(1)
    },
    async toEditSpec (info) {
      this.specsTable = info.price
      this.showSpecDialog = true
    },
    beforeClose () {
      this.showSpecDialog = false
      this.getTableDataList()
    },
    async submitFormInfo () {
      let { specsTable } = this
      let stock = []
      specsTable.map(item => {
        stock.push({ id: item.true_id, stock: item.stock || 0 })
      })
      let { code } = await this.$api.GoodsUpdateSpe({ stock })
      if (code !== 200) return
      this.$message.success(this.$t('tips.successRev'))
      this.beforeClose()
    },
    toChange (key) {
      this.searchForm.type = key
      this.searchForm.page = 1
      this.getTableDataList()
    },
    toggleSelection (rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    handleSizeChange (val) {
      this.searchForm.limit = val
      this.handleCurrentChange(1)
    },
    handleCurrentChange (val) {
      this.searchForm.page = val
      this.getTableDataList()
    },

    /**
     * @method 获取下拉菜单的选项值
     */
    getSelectOptions () {
      this.$api.GoodsListSelect().then(res => {
        if (res.code === 200) {
          let { companyOptions, cateOptions } = this
          let { cate, company } = res.data
          this.companyOptions = companyOptions.concat(company)
          this.cateOptions = cateOptions.concat(cate)
        }
      })
    },

    /**
     * @method 清除二维码
     */
    clearQrCode () {
      this.$api.clearGoodsQrCode().then(res => {
        console.log(res)
        if (res.code === 200) {
          this.$message.success('清除成功！')
        }
      })
    },

    /**
     * @method 上下架商品
     */
    upperAndDelGoods (status, id, key) {
      let param = key === 'index_show' ? { index_show: status, id } : { status, id }
      this.$api.upperAndDelGoods(param).then(res => {
        console.log(res)
        if (res.code === 200) {
          this.$message.success(this.$t(status === -1 ? 'tips.successDel' : 'tips.successOper'))
          if (status !== -1 && id.length > 1) {
            this.batchChangeSwitch(status)
          }
          if (key === 'index_show') return
          this.searchForm.page = this.searchForm.page < Math.ceil((this.total - id.length) / this.searchForm.limit) ? this.searchForm.page : Math.ceil((this.total - id.length) / this.searchForm.limit)
          this.getTableDataList()
        } else {
          if (status === -1) return
          this.getTableDataList()
        }
      })
    },

    /**
     * @method 批量获取数据ID
     */
    batchUpperAndDel (status) {
      let { multipleSelection } = this
      if (multipleSelection.length > 0) {
        let batchArr = multipleSelection.map(item => {
          return item.id
        })
        if (status === -1) {
          this.confirmDelGoods(batchArr)
        } else {
          this.upperAndDelGoods(status, batchArr)
        }
      } else {
        this.$message.warning('请选择表格数据后再批量操作')
      }
    },

    /**
     * @method 批量设置开关
     */
    batchChangeSwitch (status) {
      this.multipleSelection.forEach(item => {
        item.status = status
      })
    },
    /**
     * @method 获取商品列表
     */
    getTableDataList (flag) {
      if (flag) this.searchForm.page = 1
      this.loading = true
      let { searchForm, companyArr, cateArr } = this
      searchForm.company = companyArr[companyArr.length - 1] || ''
      searchForm.cate = cateArr[cateArr.length - 1] || ''
      this.$api.getGoodsList(searchForm).then(res => {
        this.loading = false
        if (res.code === 200) {
          this.tableData = res.data.data
          this.total = res.data.total
          this.sale_ing = res.data.sale_ing
          this.sale_end = res.data.sale_end
          this.sale_out = res.data.sale_out
        }
      })
    },

    /**
     * @method 删除单个商品
     * @param index商品下标
     * @param id商品id
     */
    confirmDelGoods (id) {
      this.$confirm(this.$t('tips.confirmDelete'), this.$t('tips.reminder'), {
        confirmButtonText: this.$t('action.comfirm'),
        cancelButtonText: this.$t('action.cancel'),
        type: 'warning'
      }).then(() => {
        this.upperAndDelGoods(-1, id)
      }).catch(() => {

      })
    }
  },
  // watch: {
  //   $route: {
  //     deep: true,
  //     handler (val) {
  //       if (val.meta.refresh) {
  //         this.$route.meta.refresh = false
  //         this.getTableDataList()
  //       }
  //     }
  //   }
  // },
  filters: {
    handleTime (val, type) {
      let time = type === 1 ? moment(val * 1000).format('YYYY-MM-DD') : type === 2 ? moment(val * 1000).format('HH:mm:ss') : moment(val * 1000).format('YYYY-MM-DD HH:mm:ss')
      return time
    }
  }
}
</script>

<style lang="scss" scoped>
.lb-goods-list {
  width: 100%;
  .page-main {
    width: 100%;
    padding: 20px;
    .shop-list-btn {
      .item-child {
      }
    }
    .el-table {
      img {
        width: 80px;
        height: 80px;
      }
    }
  }
}
</style>
